package com.juxing.service.userCenter.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.juxing.service.userCenter.IUserCenterService;
import com.juxing.service.userCenter.bean.UserBean;
import com.juxing.service.userCenter.cache.IUserCache;
import com.juxing.service.userCenter.dao.IUserDao;

/**
 * 
 * @author brochen
 * @mail mongibello@163.com
 * @created 2016年1月31日
 *
 */
public class UserCenterServiceImpl implements IUserCenterService {

	private static final Logger logger = LoggerFactory.getLogger(UserCenterServiceImpl.class);
	
	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IUserCache userCache;
	
	@Override
	public void insert(UserBean user) {
		userDao.insert(user);
		userCache.setNicknameUsed(user.getNickname(), user.getUserId());
		userCache.removeFromNicknameUnUsed(user.getNickname());
		userCache.setUser(user);
	}

	@Override
	public UserBean queryByUserId(int userId) {
		UserBean user = userCache.getUser(userId);
		if(user == null) {
			user = userDao.queryByUserId(userId);
			if(user != null) {
				userCache.setUser(user);
			}
		}
		return user;
	}
	
	@Override
	public boolean isNicknameUsed(String nickname) {
		if(userCache.getNicknameUsedUserId(nickname) > 0) {	//已经有用户使用了该昵称
			return true;
		}
		if(userCache.isNicknameUnUsed(nickname)) {	//没有人使用该昵称
			return false;
		}
		UserBean user = userDao.queryByNickname(nickname);
		if(user == null) {
			userCache.setNicknameUnUsed(nickname);
			return false;
		} else {
			userCache.setNicknameUsed(nickname, user.getUserId());
			return true;
		}
	}
	
}
